package com.fionera.sample.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.telephony.TelephonyManager

import com.fionera.sample.util.OkHttpUtil
import com.wsdk.view.ProcessDialog
import java.util.Random

/**
 * @author fionera
 */
open class BaseFragment : Fragment() {

    protected lateinit var mProcessDialog: ProcessDialog
    protected lateinit var mContext: Context
    protected lateinit var mActivity: Activity
    private var globalCode = ""

    @Suppress("DEPRECATION")
    @SuppressLint("HardwareIds")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val telephonyManager = mContext.getSystemService(Context
                .TELEPHONY_SERVICE) as TelephonyManager
        if (ActivityCompat.checkSelfPermission(mContext,
                        Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return
        }
        var imei: String? = telephonyManager.deviceId
        if (imei == null) {
            imei = Random().toString()
        }
        globalCode = imei + System.currentTimeMillis()
    }

    override fun onAttach(context: Context) {
        setHasOptionsMenu(true)
        mContext = context
        mActivity = context as Activity
        mProcessDialog = ProcessDialog(mContext)
        super.onAttach(mContext)
    }

    override fun onDestroy() {
        super.onDestroy()
        OkHttpUtil.cancelCallWithTag("OkHttpCall_" + this.hashCode())
    }

    protected fun getEnqueue(url: String, responseCallback: OkHttpUtil.NetCallBack) {
        OkHttpUtil.getEnqueue(url, responseCallback, "OkHttpCall_" + this.hashCode())
    }

    protected fun postJsonEnqueue(url: String, params: Map<String, String>,
                                  responseCallback: OkHttpUtil.NetCallBack) {
        OkHttpUtil.postJsonEnqueue(if (url.contains(
                        "?"))
            "$url&reqIdentifer=$globalCode"
        else
            "$url?reqIdentifer=$globalCode",
                params, responseCallback, "OkHttpCall_" + this.hashCode())
    }

    protected fun putJsonEnqueue(url: String, params: Map<String, String>,
                                 responseCallback: OkHttpUtil.NetCallBack) {
        OkHttpUtil.putJsonEnqueue(url, params, responseCallback, "OkHttpCall_" + this.hashCode())
    }
}
